//
//  SXQr-CodeViewController.m
//  ShiXun
//
//  Created by lanou on 15/11/4.
//  Copyright © 2015年 张琪. All rights reserved.
//

#import "SXQr-CodeViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "SXQr-CodeDetailViewController.h"

@interface SXQr_CodeViewController () <AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate>

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *layer;

@end

@implementation SXQr_CodeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.title = @"二维码扫描";
    self.view.backgroundColor = [UIColor colorWithWhite:0.651 alpha:1.000];
    
    // 获取摄像设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 创建输入流
    if (!device) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不支持此功能" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    // 创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 设置代理 在主线程里刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    // 初始化链接对象
    _session = [[AVCaptureSession alloc] init];
    // 高质量采集率
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    [_session addInput:input];
    [_session addOutput:output];
    // 设置扫码支持的编码格式（如下设置支持条形码和二维码兼容）
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    _layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    _layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _layer.frame = CGRectMake(kScreenWidth / 2 - 100, kScreenHeight / 2 - 150, 200, 200);
    [self.view.layer insertSublayer:_layer atIndex:0];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (metadataObjects.count > 0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndexedSubscript:0];
        SXQr_CodeDetailViewController *detailVC = [[SXQr_CodeDetailViewController alloc] init];
        detailVC.qrCodeString = metadataObject.stringValue;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
